package com.android.djlmapp.activity.home.web;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.base.BaseWebActivity;
import com.android.djlmapp.activity.kaika.QianMingActivity;
import com.android.djlmapp.activity.kaika.SelectNumChildActivity;
import com.android.djlmapp.activity.kaika.TiaoXingCodeScanerActivity;
import com.android.djlmapp.activity.order.OrderListActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.dialog.ChoosImgDialog;
import com.android.djlmapp.http.ComPareUtils;
import com.android.djlmapp.js_interface.BaseJsInterface;
import com.android.djlmapp.js_interface.morefun.AbMoreFunJsInterfaceCallBack;
import com.android.djlmapp.js_interface.morefun.MoreFunJsInterface;
import com.android.djlmapp.listener.read.SubReadDataListener;
import com.android.djlmapp.token.GetUrlStr;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.kaika.SubReadCardDataUtils;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.djlmapp.view.WebView4Scroll;
import com.android.readcard.activity.ReadCardActivity;
import com.android.readcard.activity.WriteCardActivity;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

import static com.android.djlmapp.activity.kaika.QianMingActivity.UPLOAD_IMG_SUCCESS_RESULT_DATA;
import static com.android.djlmapp.activity.order.OrderDetailActivity.QIANMING_INTENT_REQUEST_CODE;
import static com.android.djlmapp.activity.order.OrderDetailActivity.SELECT_SIM_NUM_REQUEST_CODE;
import static com.android.djlmapp.activity.order.OrderDetailActivity.SELECT_TEL_NUM_REQUEST_CODE;
import static com.android.djlmapp.http.GlobalUrls.BUKA_URL;
import static com.android.djlmapp.js_interface.BaseJsInterface.CALL_METHEOD_NAME;
import static com.android.djlmapp.js_interface.BaseJsInterface.CALL_METHEOD_UP_IMG_NAME;
import static com.android.djlmapp.js_interface.BaseJsInterface.MORE_FUN_JS_SIGN_KEY;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName MoreFunActivity
 * @package com.android.djlmapp.activity.home.web
 * @data 2018/12/24 16:21
 * @Describe 更多
 * @Change
 */
@RuntimePermissions
public class MoreFunActivity extends BaseWebActivity {
    private String mOrderNum = "";

    private ChoosImgDialog choosImgDialog;

    @Override
    protected void initView() {
        setWebViewClient(mWebViewClient);
        super.initView();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String str) {
            Log.e("项目异常写卡", "------shouldOverrideUrlLoading------" + str);
            if (str.contains("login_out")) {
                GetUrlStr.getStrUrl(MoreFunActivity.this);
                return true;
            }else if(str.contains("app_buka")){
                String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
                String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
                String sign = new ComPareUtils.ComPareBuilder()
                        .put("token", token)
                        .put("version", version)
                        .create()
                        .getSignString();
                // 补卡换卡
                Intent bkIntent = new Intent(MoreFunActivity.this, BukaActivity.class);
                bkIntent.putExtra(PAGE_URL_KEY, BUKA_URL + "?token=" +token + "&version=" +version + "&sign=" + sign);
                startActivity(bkIntent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, str);
        }
        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String str = request.getUrl().toString();
            Log.e("项目异常写卡", "------shouldOverrideUrlLoading------" + str);
            if (str.contains("login_out")) {
                GetUrlStr.getStrUrl(MoreFunActivity.this);
                return true;
            }else if(str.contains("app_buka")){
                String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
                String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
                String sign = new ComPareUtils.ComPareBuilder()
                        .put("token", token)
                        .put("version", version)
                        .create()
                        .getSignString();
                // 补卡换卡
                Intent bkIntent = new Intent(MoreFunActivity.this, BukaActivity.class);
                bkIntent.putExtra(PAGE_URL_KEY, BUKA_URL + "?token=" +token + "&version=" +version + "&sign=" + sign);
                startActivity(bkIntent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, request);
        }
    };
    /**
     * 设置界面不可以主动进行下拉刷新操作
     *
     * @return
     */
    @Override
    public WebView getScrollView() {
        return new WebView4Scroll(this);
    }

    @Override
    public BaseJsInterface getJsInterface() {
        return new MoreFunJsInterface(this, mMoreFunJsInterfaceCallBack, mAgentWeb);
    }

    @Override
    public String getJsInterfaceKey() {
        return MORE_FUN_JS_SIGN_KEY;
    }

    private AbMoreFunJsInterfaceCallBack mMoreFunJsInterfaceCallBack = new AbMoreFunJsInterfaceCallBack() {

        /**
         * 废卡重置
         */
        @Override
        public void fkcz() {
            // 0是废卡重置
            readIccidOrWriteCard(0);
        }

        /**
         * 废卡重置结果
         * @param msg
         */
        @Override
        public void fkczResult(String msg) {
        }

        /**
         * 派单
         */
        @Override
        public void qdpd() {
        }

        /**
         * 保存图片
         * @param url
         */
        @Override
        public void saveImg(String url) {
            mDownImgUrl = url;
            MoreFunActivityPermissionsDispatcher.onNeedPermissionWriteReadWithCheck(MoreFunActivity.this);
        }

        /**
         * 扫描身份证
         */
        @Override
        public void readIDCard() {
            startActivity(new Intent(MoreFunActivity.this, ReadCardActivity.class));
        }

        /**
         * 补卡回调
         * @param json
         */
        @Override
        public void bkSubmit(String json) {
//            try {
//                JSONObject jsonObject = new JSONObject(json);
//                mOrderNum = jsonObject.optString("order_sn");
//                if ("7".equals(jsonObject.optString("type"))) {
//                    // 开始补卡
//                    readIccidOrWriteCard(2);
//                }
//            } catch (JSONException e) {
//                ToastUtils.showShortToast(MoreFunActivity.this, "数据解析异常");
//                e.printStackTrace();
//            }

        }

        /**
         * 搜索号码
         * @param json
         */
        @Override
        public void getPhoneNum(String json) {
            // NativeRetuion
            Intent intent = new Intent(MoreFunActivity.this, SelectNumChildActivity.class);
            intent.putExtra(SelectNumChildActivity.REQUEST_PARAMS_KEY, json);
            startActivityForResult(intent, SELECT_TEL_NUM_REQUEST_CODE);
        }

        /**
         * sim卡号
         */
        @Override
        public void getSimNum() {
            Intent intent = new Intent(MoreFunActivity.this, TiaoXingCodeScanerActivity.class);
            startActivityForResult(intent, SELECT_SIM_NUM_REQUEST_CODE);
        }

        /**
         * 去订单列表
         */
        @Override
        public void goOrderList() {
            startActivity(new Intent(MoreFunActivity.this, OrderListActivity.class));
            isUseFinishAnimation = false;
            finish();
        }

        @Override
        public void getSignImg() {
            Intent intent = new Intent(MoreFunActivity.this, QianMingActivity.class);
            startActivityForResult(intent, QIANMING_INTENT_REQUEST_CODE);
        }

        @Override
        public void getImgs() {
            if (choosImgDialog == null) {
                choosImgDialog = new ChoosImgDialog(MoreFunActivity.this);
                choosImgDialog.setItemClickListener(v -> {
                    choosImgDialog.cancel();
                    switch (v.getId()) {
                        case R.id.dialog_Title_tv:
                            takePhoto();
                            break;
                        case R.id.dialog_Content_tv:
                            choosePhoto();
                            break;
                        default:
                            break;
                    }
                });
            }
            choosImgDialog.showDialog();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_TEL_NUM_REQUEST_CODE && resultCode == RESULT_OK) {
            // 选择号码
            String selectNum = data.getStringExtra(SelectNumChildActivity.SELECTED_TEL_KEY);
            mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_NAME, selectNum);
        } else if (requestCode == SELECT_SIM_NUM_REQUEST_CODE && resultCode == 0) {
            // 选择sim卡号
            Bundle str = data.getExtras();
            String result = str.getString(CodeUtils.RESULT_STRING);
            int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            if (resultType == CodeUtils.RESULT_SUCCESS) {
                if (result == null) {
                    ToastUtils.showShortToast(MoreFunActivity.this, "扫描失败，沒有扫描到卡体，请重试");
                    return;
                }
                if (result.length() >= 19) {
                    String keyvalue = result.substring(0, 19);
                    if (TextUtil.isNumeric(keyvalue)) {
                        Log.e("项目异常keyvalue", "------keyvalue------" + keyvalue);
                        // 是纯数字
                        mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_NAME, keyvalue);
                    } else {
                        ToastUtils.showShortToast(MoreFunActivity.this, "请确定您扫描的是SIM卡");
                    }
                } else {
                    ToastUtils.showShortToast(MoreFunActivity.this, "请确定您扫描的是SIM卡");
                }
            } else {
                ToastUtils.showShortToast(MoreFunActivity.this, "扫描失败，请重新扫描");
            }
        } else if (requestCode == QIANMING_INTENT_REQUEST_CODE && resultCode == 2) {
            // 签名照
            String imgUrl = data.getStringExtra(UPLOAD_IMG_SUCCESS_RESULT_DATA);
            mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_UP_IMG_NAME, imgUrl);
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.A:
                // 读卡
                BackReadInfo data = (BackReadInfo) event.getData();
                ReadCardInfo readInfo = data.getInfo();
                CardData cardData = data.getCardData();
                String chuanma = data.getChuanma();

                // 上传身份信息获取经办人数据
                SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
                    @Override
                    public void subPhotoSuc(String needJb, String photoUrl) {
                        Gson gson = new Gson();
                        String strJson = gson.toJson(cardData);
                        Log.i("上传身份证", "subPhotoSuc: " + strJson);
                        mAgentWeb.getJsAccessEntrace().quickCallJs("returnCARD", strJson);
                    }

                    @Override
                    public void subErr(String msg) {
                        ToastUtils.showShortToast(MoreFunActivity.this, msg);
                    }
                });
                break;
//            case EventCodes.EventReadCardCode.B: // 返回iccid
//                String mUrl = "";
//                ReadIccidAndWriteCardInfo iccidData = (ReadIccidAndWriteCardInfo) event.getData();
//                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo--返回iccid----" + iccidData.toString());
//                String iccidNum = iccidData.getIccidNum();
//                int writeType = iccidData.getWriteType();
//                String errMsg = iccidData.getErrMsg(); // 错误信息
//                String imsi = iccidData.getImsi(); // imsi
//                switch (writeType) {
//                    case 0: // 废卡重置
//                        WriteCardUtils.clearCard(iccidNum, imsi, new GetPhotoUrlListener() {
//                            @Override
//                            public void backPhotoUrl(int backType, String result) {
//                                // eventbus通知WriteCardActivity,废卡重置完成了,成功失败都要提示并且关闭写卡界面
//                                Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
//                                EventBusUtil.sendEvent(clearCardEvent);
//                                WriteCardUtils.showMsg(MoreFunActivity.this, "废卡重置结果", result);
//                            }
//                        });
//                        break;
//                    case 1: // 写卡
//                        mUrl = GlobalUrls.BAI_KA;
//                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
//                        WriteCardUtils.startWrite(MoreFunActivity.this, mUrl, iccidNum, mOrderNum, "写卡");
//                        break;
//                    case 2: // 补卡
//                        mUrl = GlobalUrls.BU_KA;
//                        // 上传iccid获取短信中心号和imsi并eventbus返回给WriteCardActivity
//                        WriteCardUtils.startWrite(MoreFunActivity.this, mUrl, iccidNum, mOrderNum, "补卡");
//                        break;
//                    default:
//                        break;
//                }
//                break;
//            case EventCodes.EventReadCardCode.D: // 返回写卡结果
//                String sucUrl = "";
//                ReadIccidAndWriteCardInfo xiekaData = (ReadIccidAndWriteCardInfo) event.getData();
//                Log.e("项目异常写卡", event.getCode() + "------ReadIccidAndWriteCardInfo-返回写卡结果-----" + xiekaData.toString());
//                String iccidNum1 = xiekaData.getIccidNum();
//                int writeType1 = xiekaData.getWriteType();
//                String errMsg1 = xiekaData.getErrMsg(); // 错误信息
//                String imsi1 = xiekaData.getImsi(); // imsi
//                // 判断errMsg是不是空,是空值就是写卡成功
//                if (TextUtils.isEmpty(errMsg1)) {
//                    boolean isRefWeb = false; // TODO 是否需要刷新web
//                    switch (writeType1) {
//                        case 1:
//                            sucUrl = GlobalUrls.BAI_KA_OK;
//                            isRefWeb = WriteCardUtils.writeSucSubmit(MoreFunActivity.this, sucUrl, iccidNum1, mOrderNum, "写卡");
//                            break;
//                        case 2:
//                            sucUrl = GlobalUrls.BU_KA_OK;
//                            isRefWeb = WriteCardUtils.writeSucSubmit(MoreFunActivity.this, sucUrl, iccidNum1, mOrderNum, "补卡");
//                            Log.e("项目异常写卡isRefWeb", "---写卡成功---isRefWeb2222------" + isRefWeb);
//                            break;
//                        default:
//                            break;
//                    }
//
//                } else {
//                    // 写卡失败,提示错误
//                    Event<String> clearCardEvent = new Event<>(EventCodes.EventReadCardCode.E);
//                    EventBusUtil.sendEvent(clearCardEvent);
//                    switch (writeType1) {
//                        case 1:
//                            WriteCardUtils.showMsg(MoreFunActivity.this, "写卡结果", errMsg1);
//                            break;
//                        case 2:
//                            WriteCardUtils.showMsg(MoreFunActivity.this, "补卡结果", errMsg1);
//                            break;
//                        default:
//                            break;
//                    }
//                }
//                break;
//            default:
//                break;
        }
    }

    private void readIccidOrWriteCard(final int mType) {
        // 蓝牙对话框
        startActivity(new Intent(MoreFunActivity.this, WriteCardActivity.class).putExtra("WriteType", mType));
    }

    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> images = result.getImages();
        String compressPath = images.get(0).getCompressPath();
        if (compressPath != null && !TextUtils.isEmpty(compressPath)) {
            File file = new File(compressPath);
            MyApplication.getInstance().getHttpTools().upLoadImg(file, new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs(CALL_METHEOD_UP_IMG_NAME, response.body());
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    showToast(getString(R.string.connect_sever_error_msg));
                }
            });
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        runOnUiThread(() -> showToast("压缩失败：" + msg));
    }

    private String mDownImgUrl;

    private void downImg() {
        Glide.with(MoreFunActivity.this).asBitmap().load(mDownImgUrl).listener(new RequestListener<Bitmap>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                showToast("保存失败，请检查网络");
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                saveImageToGallery(resource);
                return false;
            }
        }).submit();
    }

    /**
     * 保存图片
     *
     * @param bmp
     * @return
     */
    private void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download" + File.separator + "Djlm";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = "zcord.jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            showToast("图片已保存");
        } catch (Exception e) {
            e.printStackTrace();
            showToast("保存失败");
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeedPermissionWriteRead() {
        downImg();
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onDeniedWriteRead() {
        showToast("暂无权限");
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRational(final PermissionRequest request) {
        request.proceed();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MoreFunActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


}
